package com.yet.center;

import java.util.Arrays;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;

import com.yet.exception.ConfigException;
import com.yet.listener.YetListener;

public abstract class ConfigCenter {

	public static final String ROOT = "/yet";

	public static final String PROP_PROFILE = "config.profile";
	public static final String DEFAULT_PROFILE = "default";

	protected String profile = DEFAULT_PROFILE;

	public abstract <T> T getValue(String path, Class<T> clz) throws ConfigException;

	public abstract Object getValue(String path) throws ConfigException;

	public abstract void setValue(String path, Object data) throws ConfigException;

	public abstract void subscribe(String path, YetListener listener) throws ConfigException;

	public abstract void unSubscribe(String path) throws ConfigException;

	public abstract List<String> getRoot() throws ConfigException;

	public abstract Map<String, Object> load() throws ConfigException;

	public String getProfile() {
		return profile;
	}

	public void setProfile(String profile) {
		this.profile = profile;
	}

	protected static String getPath(String... path) {
		return String.join("/", Arrays.stream(path).filter(p -> StringUtils.isNotBlank(p)).toArray(i -> new String[i]));
	}

	protected String getWholePath(String path) {
		return getPath(ROOT, profile, path);
	}

	protected String getProfilePath() {
		return ROOT + "/" + getProfile();
	}

	public static String extractKey(String profile, String path) {
		return path.replace(getPath(ROOT, profile) + "/", "");
	}
}
